/*This is the server javascript for ee-ut-battleship created by Marko Tiidla and Priit Tiidla*/


this.ServerShip = function(id, itselfString, nodropString){
	this.id = id;
	this.itselfString = itselfString;
	this.nodropString = nodropString;
};


this.findOpponent = function(){
	var result = 0;
	$.ajax({
		  type: 'GET',
		  url: "JoinGame",
		  dataType: "text",
		  data: "clientName=" + FBstate,
		  success: function(data){
			  if (data == "newgame"){
				  result = 1;
				  setTimeout("activateBattleSystem()", 1000);
			  } else {
				  findOpponent();
			  }
		  }
	});
	return result;
};
/*this.sendLoginToServer = function(){
	
	$.ajax({
		  type: 'POST',
		  url: "LoginServlet",
		  data: "clientName=" + FBstate,
		  dataType: "text"
		  
	});
};
*/
this.sendLogOutToServer = function(){
	
	$.ajax({
		  type: 'GET',
		  url: "LoginServlet",
		  data: "clientName=" + FBstate
	});
};


this.sendShipList = function(shiplist) {
	
	
	var serverShipList = new Array();
	for ( i in shiplist){
		
		var itselfId = "";
		for (j in shiplist[i].itself){
			var string = shiplist[i].itself[j].id;
			itselfId += string + " ";
		}
		
		var nodropId = "";
		for (j in shiplist[i].nodrop){
			var string = shiplist[i].nodrop[j].id;
			nodropId += string + " ";
		}
		
		nodropId += itselfId;
		
		serverShipList.push(new ServerShip(shiplist[i].id,itselfId, nodropId));
	}
	var serverShipList = JSON.stringify(serverShipList);

	$.ajax({
		  type: 'POST',
		  url: "ShipOperator",
		  data: "shiplist=" + serverShipList +"&clientName=" + FBstate,
		  dataType: "json",
		  success: function() {
			  
			  if (validateShipsWithServer()==true){
				  playerTurn = getFirstTurn();
				  startGame();
					document.getElementById("newgame").innerHTML = "M&auml;ng k&auml;ib";
					$('#newgame').attr('onclick','').unbind('click');
					getEnemyShot();
			  }
			  else {
				  alert("Your ships are wrong!!!");
			  }
			  }
		});
};
 
/**
 * This function sends request to server, to get result about the shoot
 * @param id square id on enemy board where played clicked on
 */
this.shoot = function(id) {
	var result = -1;
	$.ajax({
		type: 'POST',
		url: "Shoot",
		data: "shotid=" + id+"&clientName=" + FBstate,
		async: false,
		  success: function (data) {result = data;},
		  dataType: "text"
		});
	return result;
};

this.validateShipsWithServer = function() {
	var result = false;
	$.ajax({
		  type: 'GET',
		  url: "ShipValidation",
		  async: false,
		  cache: false,
		  dataType: "text",
		  data: "clientName=" + FBstate,
		  success: function (validated) {
			  
			  result =  validated=="1";
		  }
	});
	return result;
};

//hitArray is used to store shots, to avoid duplicate shots by computer
var hitArray = new Array();
/**
 * Server is queried for enemy shot, player waits until response is aquired.
 * NB! at the moment computer makes shots.
 */
this.getEnemyShot = function() {

	$.ajax({
		  type: 'GET',
		  url: "Shoot",
		  async: true,
		  cache: false,
		  data: "clientName=" + FBstate,
		  dataType: "text",
		  success: function (enemyShot) {
			  if (enemyShot != "-1"){
				  var hit = hitBoard(enemyShot, fullBoard, SHIPLIST);
					if (hit == 1){
						playerTurn = false;
						$("#player").removeClass("turn");
						$("#opponent").addClass("turn");

					} else if (hit == 2){
						loss();
						return;
					} else {
						playerTurn = true;
						$("#player").addClass("turn");
						$("#opponent").removeClass("turn");
	
					}
			  }
			  getEnemyShot(); 
		  }
		});
};


$(document).ready(function() {
	getFacebookInfo();
	
	var uri = document.URL;
	var code = getParameterByName('code');
	if (code != null) {
		getFBLogin(code);
	}
});

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return null;
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

this.client = null;
/*this.getLoginFromServer = function() {
	$.ajax({
		  async: false,
		  type: 'GET',
		  url: "ExistingLogin",
		  data: "clientName=" + client,
		  dataType: "text",
		  success: function(data){
			  
			  var result = data;
			  if (result != "null") {
				  
				  client = result;
			  } else {
				  client = null;
			  }
			  
			  drawLoginWindow();
		  }
			  
		});
};
*/

this.FBstate = null;
this.FBredirect = null;
this.FBAppID = null;
this.getFacebookInfo = function() {
	$.ajax({
		  async: false,
		  type: 'POST',
		  url: "FacebookInfo",
		  dataType: "text",
		  success: function(data){
			  
			  var result = data.split(";");
			  FBstate = result[0];
			  FBredirect = result[1];
			  FBAppID = result[2];
		  }
		});
};

this.getFBLogin = function(code) {
	$.ajax({
		  type: 'GET',
		  url: "FacebookInfo",
		  data: "code="+code +"&state=" +FBstate,
		  dataType: "text",
		  success: function(data){
			  
			  var result = data;
			  if (result != "null"){ 
				  client = result;
				  displayLogin();
			  }
		  }
		});
};

this.addNewGame = function(client) {
	$.ajax({
		  type: 'POST',
		  url: "AddNewGame",
		  async: true,
		  dataType: "text",
		  data: "clientName="+client
		  
			  
		});
	
};

this.joinGame = function(client){
	var opponent = "";
	
	if (GAMES[selectedRowNr].playerOne == client){
		opponent = GAMES[selectedRowNr].playerTwo;
	} else {
		opponent = GAMES[selectedRowNr].playerOne;
	}
	
	$.ajax({
		  type: 'POST',
		  url: "JoinGame",
		  async: true,
		  dataType: "text",
		  data: "opponentName="+opponent+"&selectedGame="+selectedRowNr+"&clientName="+client,
		  success: function () {
			  
		  }
			  
		});
};

this.updateLobby = function() {
	var result;
	$.ajax({
		  type: 'GET',
		  url: "UpdateLobby",
		  async: true,
		  dataType: "text",
		  cache: false,
		  data: "clientName=" + client,
		  complete: function() {
			  
			  forceUpdateLobby();
			  updateLobby();
			  
		  }
		
		});
	
};

this.forceUpdateLobby = function() {
	var result;
	$.ajax({
		  type: 'POST',
		  url: "UpdateLobby",
		  async: false,
		  dataType: "text",
		  cache: false,
		  data: "clientName=" + client,
		  success: function (data) {
			  
			  GAMES = new Array();
			  var object = jQuery.parseJSON(data);
			  for (i in object){
				  GAMES.push(new Game(object[i].playerOne,object[i].playerTwo));
			  }
			  if (gameIsActive==false){
				  drawLobby();
			  }
		  }
	});
};

this.updateHighscore = function() {
	$.ajax({
		  type: 'GET',
		  url: "UpdateHighscore",
		  async: true,
		  dataType: "text",
		  cache: false,
		  data: "clientName=" + client,
		  complete: function() {
			  drawHighscores();
			  updateHighscore();
		  }
		});
};

this.getFirstTurn = function() {
	var result = 1;
	$.ajax({
		  type: 'GET',
		  url: "TurnPicker",
		  async: false,
		  data: "clientName=" + client,
		  success: function (data) {
			  result = data;
			  if (result==1){
				  $("#player").addClass("turn");
				  $("#opponent").removeClass("turn");

				  
			  } else {
				  $("#opponent").addClass("turn");
				  $("#player").removeClass("turn");

			  }
				
		  },
		  dataType: "text"
		});
	
	return result==1;
};

function populateWithScore() {
	var result = -1;
	$.ajax({
		  type: 'GET',
		  url: "SQL",
		  async: false,
		  data: "clientName=" + client,
		  success: function (data) {
			  result = data;
		  },
		  dataType: "text"
		});
	return result;
}


